package com.binguo.wxapi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.enums.SbConfigKey;
import com.binguo.common.enums.ZSDWXMessageTitle;
import com.binguo.common.exception.ErrorCode;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.sms.JavaSmsApi;
import com.binguo.common.sms.SMS;
import com.binguo.common.util.DateUtil;
import com.binguo.common.util.Jpush.push.JPushUtil;
import com.binguo.common.util.UrlUtils;
import com.binguo.helper.FaceHelperV3;
import com.binguo.helper.WxAppHelper;
import com.binguo.model.api.vo.BinguoOrderVO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.wxapi.form.ZSDOrderInfoForm;
import com.binguo.model.wxapi.form.ZSDWXGongZhongMessageForm;
import com.binguo.model.wxapi.vo.AiyouweiGetCellVO;
import com.binguo.model.wxapi.vo.OpenCellByCardNoVO;
import com.binguo.model.wxapi.vo.SideBoardVO;
import com.binguo.model.wxapi.vo.UmengPushVo;
import com.binguo.service.NormalConfigService;
import com.binguo.service.QrCodePayQCGService;
import com.binguo.wxapi.controller.ApiController;
import com.binguo.wxapi.form.PhoneMealsForm;
import com.binguo.wxapi.form.aiyouwei.BindCustomerBoardForm;
import com.binguo.wxapi.form.aiyouwei.SaveOrderForm;
import com.binguo.wxapi.util.BarcodeUtil;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;


@Scope(proxyMode = ScopedProxyMode.INTERFACES)
@Service
public class AiyouweiTestServiceImpl implements AiyouweiTestService {

    private static final Logger logger = LoggerFactory.getLogger(AiyouweiTestServiceImpl.class);

    @Resource
    private ShopConfigExtendMapper shopConfigExtendMapper;

    @Resource
    private SideBoardCellsMapper sideBoardCellsMapper;

    @Resource
    private BinguoOrderMapper binguoOrderMapper;

    @Resource
    private SideBoardCellDetailMapper sideBoardCellDetailMapper;

    @Resource
    private SideBoardMapper sideBoardMapper;

    @Resource
    private PayCardMapper payCardMapper;

    @Resource
    private YpCardMapper ypCardMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private CustomerMapper customerMapper;

    @Autowired
    private AiyouweiService aiyouweiService;

    @Autowired
    private QrCodePayQCGService qrCodePayQCGService;

    @Resource
    private InitInfoMapper initInfoMapper;

    @Resource
    private RedisLockService redisLockService;

    @Resource
    NormalConfigService normalConfigService;

    @Resource
    private ThirdOrderDataMapper thirdOrderDataMapper;

    @Resource
    WxPushMessageDetailMapper wxPushMessageDetailMapper;

    @Resource
    SbConfigMapper sbConfigMapper;

    @Resource
    SbBindProductToCellMapper sbBindProductToCellMapper;

    @Resource
    ProductMapper productMapper;

    @Resource
    ApiService apiService;

    @Resource
    SbThirdOrderMapper sbThirdOrderMapper;

    @Resource
    SbThirdOrderDetailMapper sbThirdOrderDetailMapper;

    @Resource
    ShopConfigMapper shopConfigMapper;


    private String token = "";

    private static String ipAddress = System.getenv("ipAddress");
    public String wxapiFilepath = "/usr/local/nginx/html";

    @Override
    public SideBoardVO getIsWramAndIsMeals(SideBoardVO sideBoardVO) {
        return shopConfigExtendMapper.selectByShopIdAndBranchId(sideBoardVO.getShopId(), sideBoardVO.getBranchId());
    }

    @Override
    public Integer addShopConfigExtend(SideBoardVO sideBoardVO) {
        ShopConfigExtend shopConfigExtend =
                new ShopConfigExtend(0, sideBoardVO.getShopId(), sideBoardVO.getBranchId(), sideBoardVO.getWarm(), sideBoardVO.getPrice());
        return shopConfigExtendMapper.insert(shopConfigExtend);
    }

    @Override
    public Integer updateShopConfigExtend(SideBoardVO sideBoardVO) {
        return shopConfigExtendMapper.updateShopConfigExtendById(sideBoardVO.getId(), sideBoardVO.getWarm(), sideBoardVO.getPrice());
    }

    @Override
    public SideBoardVO getOrderSideBoardVO(BinguoOrderVO binguoOrderVO, String orderId) {
        SideBoardVO sideBoardVO = shopConfigExtendMapper.selectByShopIdAndBranchId(binguoOrderVO.getShopId(), binguoOrderVO.getBranchId());
        Integer branchShopId = sideBoardCellsMapper.selectShopBranchId(orderId);
        sideBoardVO.setBranchId(binguoOrderVO.getBranchId());
        sideBoardVO.setShopId(binguoOrderVO.getShopId());
        sideBoardVO.setSideBranchId(branchShopId);
        if (binguoOrderVO.getIsMeals() == 0) {
            sideBoardVO.setPrice(null);
            sideBoardVO.setWarm(null);
        } else {
            if (binguoOrderVO.getIsWarm() == 0) {
                sideBoardVO.setWarm(null);
            }
        }
        return sideBoardVO;
    }

    @Override
    public String getQrCode(SaveOrderForm saveOrderForm) {
        //1.根据订单号查找出订单
        BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
        //2.根据订单号查找出该订单餐盘所在格
        String mealCode =
                sideBoardCellDetailMapper.selectMealCodeByOrderNoAndShopIdAndBranchId(binguoOrder.getOrderno(), binguoOrder.getBranchid(), binguoOrder.getShopid());
        saveOrderForm.setMealCode(mealCode);
        saveOrderForm.setBranchId(binguoOrder.getBranchid());
        saveOrderForm.setShopId(binguoOrder.getShopid());
        //实体类转String后调用二维码生成接口
        return BarcodeUtil.generateFile7(JSON.toJSONString(saveOrderForm));
    }

    /**
     * 存餐码存餐 涉及到多表插入或更新操作，所以采用事务
     *
     * @param saveOrderForm
     * @return true : false
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByMealCode(SaveOrderForm saveOrderForm) {
        String orderId = "";
        if (!StringUtils.isBlank(saveOrderForm.getOrderId())) {
            orderId = saveOrderForm.getOrderId();
        } else {
            orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        }
        if (StringUtils.isEmpty(orderId)) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        Integer status = sideBoardCellDetailMapper.selectStatus(orderId);
        if (null == saveOrderForm.getType()) {
            saveOrderForm.setType(0);
        }
        if (saveOrderForm.getType() != 1 && status >= 1) {
            return ErrorCode.SAVE_ORDER_FAIL;
        }
        saveOrderForm.setOrderId(orderId);
        BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(orderId);
        AiyouweiGetCellVO aiyouweiGetCellVO = selectAllNotUseCell(saveOrderForm.getBranchId(), saveOrderForm.getShopId());
        String[] cellNo = new String[]{aiyouweiGetCellVO.getCell().toString()};
        SideBoard sideBoard = getSideBoardById(aiyouweiGetCellVO.getSideBoardId());
        if (aiyouweiGetCellVO == null) {
            return ErrorCode.CELLS_NOT_ENOUGH;
        }

        String mealCode = isMealCodeExist(orderId, saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (mealCode == null || mealCode.equals("")) {
            mealCode = getMealCode(saveOrderForm.getBranchId());
        }
        SideBoardCells boardCells = SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
                status(true).cell(aiyouweiGetCellVO.getCell()).
                orderId(saveOrderForm.getOrderId()).mealCode(mealCode).
                sideBoardId(aiyouweiGetCellVO.getSideBoardId()).isWarm(false).build();
        saveOrderForm.setMealCode(mealCode);
        return saveOrderUpdateRecord(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo);
    }

    /**
     * 取餐码取餐 涉及到多表插入或更新操作，所以采用事务
     *
     * @param saveOrderForm
     * @return true : false
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode getOrderByMealCode(SaveOrderForm saveOrderForm) throws Exception {
        String[] mealCodes = saveOrderForm.getMealCode().split(",");
        //String orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        List<String> orderIds = getBinguoOrderIdByMealCodes(mealCodes, saveOrderForm.getShopId(), saveOrderForm.getBranchId());
//        if (StringUtils.isEmpty(orderId)) {
//            return ErrorCode.CUSTOMER_NOT_ORDER;
//        }
        if (orderIds.size() <= 0 || null == orderIds) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        //saveOrderForm.setOrderId(orderId);
        saveOrderForm.setOrderIds(orderIds);
        //BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(orderId);
        List<BinguoOrderVO> binguoOrderVOS = binguoOrderMapper.findIsMealByOrderNos(orderIds);
        //List<SideBoardCells> slist = sideBoardCellsMapper.selectByOrderId(saveOrderForm.getOrderId());
        List<SideBoardCells> slist = sideBoardCellsMapper.selectByOrderIds(saveOrderForm.getOrderIds());
        if (slist.size() <= 0) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(slist.get(0).getSideBoardId());
        if (null != sideBoard) {
            if (!sideBoard.getCashierDeskId().equals(saveOrderForm.getCashierDeskId())) {
                ErrorCode errorCode = ErrorCode.ORDER_NOT_IN_THIS_BOARD;
                errorCode.setData(sideBoard.getSideBoardName());
                return errorCode;
            }
        } else {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
        //List<SideBoardCellDetail> list = sideBoardCellDetailMapper.selectSaveOrderDetail(saveOrderForm.getOrderId(), saveOrderForm.getMealCode());
        List<SideBoardCellDetail> list = sideBoardCellDetailMapper.selectSaveOrderDetails(saveOrderForm.getOrderIds(), mealCodes);
        if (list.size() > 0) {
            String[] cellNo = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                cellNo[i] = list.get(i).getCell();
            }
            //saveOrderForm.setPhone(binguoOrderVO.getCustomerPhone());
            saveOrderForm.setPhone(binguoOrderVOS.get(0).getCustomerPhone());
            String cellNoNum = "";
            for (int i = 0; i < cellNo.length; i++) {
                cellNoNum += cellNo[i];
                if (i <= cellNo.length - 2) {
                    cellNoNum += ",";
                }
            }
            if (10 == binguoOrderVOS.get(0).getOrderType()) {
                saveOrderForm.setOrderDetailUrl(null);
                saveOrderForm.setCellNo(cellNoNum);
                String host = getConfigUrl(1);
                String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                String time = sdf.format(list.get(0).getStartTime());
                saveOrderForm.setShopPhone(normalConfigService.getConfigById(4).getValue());
                ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = getZSDWXGongZhongMessageForm(saveOrderForm, sideBoard.getSideBoardName(), ZSDWXMessageTitle.ORDER_GET_TITLE.getTitle(), time, null);
                CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
                    //异步发送取餐信息
                    sendWXGongZhoneMessage(binguoOrderVOS.get(0).getOpenId(), host, zsdwxGongZhongMessageForm);
                    return true;
                });
            }
            if (saveOrderForm.getOrgin() == null) {
                saveOrderForm.setOrgin(0);
            }
            if (saveOrderForm.getOrgin() == 1) {
                return getOrderUpdateRecordReturnCode(null, list, cellNo, sideBoard, slist, 2, saveOrderForm);
            } else {
                return getOrderUpdateRecord(null, list, cellNo, sideBoard, slist, 2, saveOrderForm);
            }

        } else {
            logger.info("当前取餐柜无剩余柜格。");
            return ErrorCode.CELLS_NOT_ENOUGH;
        }
    }

    @Override
    public String getBinguoOrderId(String mealCode, Integer shopId, Integer branchId) {
        return sideBoardCellDetailMapper.selectOrderIdByShopIdAndBranchIdAndMealCode(mealCode, branchId, shopId);
    }

    @Override
    public BinguoOrderVO getBinguoOrderByOrderNo(String orderNo) {
        return binguoOrderMapper.findIsMealByOrderNo(orderNo);
    }

    @Override
    public AiyouweiGetCellVO selectAllNotUseCell(Integer branchId, Integer shopId) {
        return sideBoardMapper.selectAllNotUseCell(branchId, shopId);
    }

    @Override
    public SideBoard getSideBoardById(Integer id) {
        return sideBoardMapper.selectByPrimaryKey(id);
    }

    @Override
    public String isMealCodeExist(String orderNo, Integer shopId, Integer branchId) {
        return sideBoardCellDetailMapper.selectMealCodeByOrderNoAndShopIdAndBranchId(orderNo, branchId, shopId);
    }

    @Override
    public String getMealCode(Integer branchId) {
        List<String> list = sideBoardCellDetailMapper.selectAllMealCodeInBranch(branchId);
        return getNewArray(list);
    }

    /**
     * 生成随机不重复取餐码方案
     *
     * @param array
     * @return
     */
    public String getNewArray(List<String> array) {
        String k = "";
        while (true) {
            String s = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
            for (int i = 0; i < array.size(); i++) {
                if (s.equals(array.get(i))) {
                    k = array.get(i);
                }
            }
            if (!s.equals(k)) {
                return s;
            } else {
                continue;
            }
        }
    }

    @Override
    public Boolean sendJpush(BinguoOrderVO binguoOrderVO, SideBoard sideBoard, String[] cellNo) {
        UmengPushVo pushVo = new UmengPushVo();
        pushVo.setCellNo(cellNo);

        //设置提示信息,内容是文章标题
        //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
        if (null != binguoOrderVO) {
            //存餐开灯
            pushVo.setLight(true);
            pushVo.setOpen(true);
            if (null != binguoOrderVO.getIsWarm()) {
                if (binguoOrderVO.getIsWarm() == 1) {
                    pushVo.setWarm(true);
                } else {
                    pushVo.setWarm(false);
                }
            }
        } else {
            //取餐关灯
            pushVo.setLight(false);
            pushVo.setWarm(false);
            pushVo.setOpen(true);
        }
        String str = JSON.toJSONString(pushVo);
        logger.info("调用开柜接口:" + pushVo);
        Map<String, String> parm = new HashMap<String, String>();
        parm.put("msg", str);
        parm.put("id", sideBoard.getJpushRegisterId());
        return JPushUtil.jpushAndroid(parm);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderUpdateRecord(SideBoardCells boardCells, SaveOrderForm saveOrderForm, BinguoOrderVO binguoOrderVO, SideBoard sideBoard, String[] cellNo) {
        //只回滚以下异常，
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            sideBoardCellsMapper.updateSideBoardCells(boardCells);
            List<SideBoardCellDetail> sideBoardCellDetails = sideBoardCellDetailMapper.selectByOrderId(saveOrderForm.getOrderId());
            List<SideBoardCells> sideBoardCells = sideBoardCellsMapper.selectByOrderId(saveOrderForm.getOrderId());
            if (sideBoardCells.size() <= sideBoardCellDetails.size()) {
                //这里当初为什么会选用get(0)的方式呢？
                sideBoardCellDetails.get(0).setStartTime(new Timestamp(System.currentTimeMillis()));
                sideBoardCellDetails.get(0).setCell(boardCells.getCell().toString());
                sideBoardCellDetails.get(0).setOrderStatus(1);
                sideBoardCellDetails.get(0).setSideBoardId(sideBoard.getId());
                logger.info("存餐更新:sideBoardCellDetail:" + sideBoardCellDetails);
                sideBoardCellDetailMapper.updateByPrimaryKeySelective(sideBoardCellDetails.get(0));
            } else {
                SideBoardCellDetail sideBoardCellDetail =
                        new SideBoardCellDetail(0, saveOrderForm.getOrderId(), new Timestamp(System.currentTimeMillis()),
                                saveOrderForm.getBranchId(), saveOrderForm.getShopId(), saveOrderForm.getMealCode(), boardCells.getCell().toString(), 1, sideBoard.getId(), saveOrderForm.getPhone() == null ? null : saveOrderForm.getPhone());
                logger.info("存餐新建sideBoardCellDetail:" + sideBoardCellDetail);
                sideBoardCellDetailMapper.insertSelective(sideBoardCellDetail);
            }
            boolean flag = sendJpush(binguoOrderVO, sideBoard, cellNo);
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ErrorCode.JPUSH_FAIL;
            }
            if (!StringUtils.isEmpty(saveOrderForm.getHost())) {
                CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
                    //异步发送取餐信息
                    updateZSDOrderStatus(saveOrderForm);
                    return true;
                });

            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            //try  catch 结构和@Transactional同样监听的是Exception类，所以这里自动回滚不会生效，手动加上回滚语句
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(cellNo);
        return errorCode;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode getOrderUpdateRecord(BinguoOrderVO binguoOrderVO, List<SideBoardCellDetail> list, String[] cellNo, SideBoard sideBoard, List<SideBoardCells> slist, Integer status, SaveOrderForm saveOrderForm) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setOrderStatus(status);
            list.get(i).setEndTime(new Timestamp(System.currentTimeMillis()));
        }
        List<SideBoardCells> sideBoardCells = new ArrayList<>();
        for (SideBoardCells sideBoardCell : slist) {
            sideBoardCell.setStatus(false);
            sideBoardCell.setOrderId("");
            sideBoardCell.setMealCode("");
            sideBoardCell.setIsWarm(false);
            sideBoardCells.add(sideBoardCell);
        }
        //只回滚以下异常，
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            sideBoardCellDetailMapper.updateSideBoardCellDetailsByList(list);
            sideBoardCellsMapper.updateSideBoardCellsByList(sideBoardCells);
            boolean flag = sendJpush(null, sideBoard, cellNo);
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ErrorCode.JPUSH_FAIL;
            }
            if (saveOrderForm != null) {
                saveOrderForm.setType(2);
                if (!StringUtils.isEmpty(saveOrderForm.getHost())) {
                    CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
                        //异步发送取餐信息
                        updateZSDOrderStatus(saveOrderForm);
                        return true;
                    });
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            //try  catch 结构和@Transactional同样监听的是Exception类，所以这里自动回滚不会生效，手动加上回滚语句
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ErrorCode.EXCEPTION_ROLLBACK;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(cellNo);
        return errorCode;
    }

    @Override
    public ErrorCode getShopOrderStatus(String orderId) {
        List<SideBoardCellDetail> sideBoardCellDetail = sideBoardCellDetailMapper.selectOrderStatus(orderId);
        Map<String, Object> map = new HashMap<>(16);
        if (sideBoardCellDetail.size() < 1) {
            map.put("code", "0");
            ErrorCode errorCode = ErrorCode.SUCCESS;
            errorCode.setData(map);
            return errorCode;
        }
        boolean flag = false;
        //循环订单表
        for (SideBoardCellDetail s : sideBoardCellDetail) {
            if (s.getOrderStatus() == 2) {
                flag = true;
            } else {
                if (s.getOrderStatus() == 0) {
                    map.put("code", "0");
                } else {
                    map.put("code", "1");
                }
                flag = false;
            }
        }
        String mealCode = sideBoardCellDetailMapper.selectMealCode(orderId);
        map.put("mealCode", mealCode);
        ErrorCode errorCode = ErrorCode.SUCCESS;
        if (!flag) {
            errorCode.setData(map);
        } else {
            map.put("code", "2");
            errorCode.setData(map);
        }
        return errorCode;
    }

    @Override
    public List<SideBoardCells> selectAllSideBoardCell(Integer id) {
        return sideBoardCellsMapper.selectAllSideBoardCell(id);
    }

    @Override
    public List<SideBoard> getBranchSideBoard(Integer branchId, Integer shopId) {
        return sideBoardMapper.selectBranchSideBoard(branchId, shopId);
    }

    @Override
    public List<SideBoard> getShopSideBoard(Integer shopId) {
        return sideBoardMapper.selectShopSideBoard(shopId);
    }

    @Override
    public ErrorCode openCellsByCellNo(String cells, Integer id) {
        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(id);
        boolean flag = sendJpush(null, sideBoard, cells.split(","));
        return flag ? ErrorCode.SUCCESS : ErrorCode.FAIL;
    }

    @Override
    public ErrorCode isTrueCode(String mealCode) {
        List<SideBoardCellDetail> list = sideBoardCellDetailMapper.isTrueMealCode(mealCode);
        return list.size() > 0 ? ErrorCode.SUCCESS : ErrorCode.MEAL_CODE_ERROR;
    }

    @Override
    public ErrorCode getOrderByCustomerCode(SaveOrderForm saveOrderForm) {
        PayCard payCard = payCardMapper.selectByPayCode(saveOrderForm.getCustomerCode());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -1);
        Date date = calendar.getTime();
        if (payCard == null) {
            return ErrorCode.WX_PAYCARD_NOT_EXIST;
        }
        if (date.after(payCard.getPayCodeTime())) {
            return ErrorCode.PAYCARD_PAYCODE_INVALID;
        }

        //更新SideBoardCellDetail和 sideBoardCells
        return readyOpenCell(payCard.getCustomerid(), saveOrderForm.getCashierDeskId());
    }

    @Override
    public ErrorCode openByCustomerCodeOrCardUpdateRecord(List<OpenCellByCardNoVO> list, SideBoard sideBoard, String[] cellNo) {
        try {
            List<SideBoardCells> sideBoardCellList = new ArrayList<>();
            List<SideBoardCellDetail> sideBoardCellDetails = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
                sideBoardCellDetail.setParams(list.get(i).getId(), new Timestamp(new Date().getTime()), 2);
                SideBoardCells sideBoardCells =
                        sideBoardCellsMapper.selectByCellAndMealCodeAndOrderNo(Integer.valueOf(list.get(i).getCell()),
                                list.get(i).getMealCode(), list.get(i).getOrderId());
                sideBoardCells.setParam(false, false, "", "");
                sideBoardCellList.add(sideBoardCells);
                sideBoardCellDetails.add(sideBoardCellDetail);
            }
            sideBoardCellsMapper.updateSideBoardCellsByList(sideBoardCellList);
            sideBoardCellDetailMapper.updateSideBoardCellDetailsByList(sideBoardCellDetails);
            boolean flag = sendJpush(null, sideBoard, cellNo);
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ErrorCode.JPUSH_FAIL;
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            //try  catch 结构和@Transactional同样监听的是Exception类，所以这里自动回滚不会生效，手动加上回滚语句
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        return ErrorCode.SUCCESS;
    }

    @Override
    public ErrorCode getOrderByPayCard(SaveOrderForm saveOrderForm) {
        String cardNo = ypCardMapper.getCardNoByCardMenjinId(saveOrderForm.getCardNo());
        PayCard payCard = payCardMapper.selectPayCardByCardNo(cardNo);
        return readyOpenCell(payCard.getCustomerid(), saveOrderForm.getCashierDeskId());
    }

    @Override
    public ErrorCode readyOpenCell(Integer customerId, Integer cashierDeskId) {
        List<OpenCellByCardNoVO> openCellByCardNoForm = sideBoardCellDetailMapper.selectByCustomerId(customerId);
        if (openCellByCardNoForm.size() <= 0) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        logger.info("根据订单id从数据库中查找cashierId,orderId:" + openCellByCardNoForm.get(0).getOrderId());
        List<Integer> sideBoardId = sideBoardCellsMapper.selectSideboardIdByOrderId(openCellByCardNoForm.get(0).getOrderId());
        if (null == sideBoardId || sideBoardId.isEmpty()) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(sideBoardId.get(0));
        //如果查询出来了就开柜
        String[] cellNo = new String[openCellByCardNoForm.size()];
        for (int i = 0; i < openCellByCardNoForm.size(); i++) {
            cellNo[i] = openCellByCardNoForm.get(i).getCell();
        }
        return openByCustomerCodeOrCardUpdateRecord(openCellByCardNoForm, sideBoard, cellNo);
    }

    @Override
    public ErrorCode getOrderByFace(SaveOrderForm saveOrderForm) {
        return saveCustomerImage(saveOrderForm);
    }

    ErrorCode saveCustomerImage(SaveOrderForm saveOrderForm) {
        String imgName = System.currentTimeMillis() + "";

        String filePath = "/usr/local/nginx/html/images/faces/" + imgName + ".png";

        String fileUrl = filePath.replace(wxapiFilepath, "http://" + ipAddress);

//        String filePath = "/usr/local/nginx/html/images/faces/" + imgName + ".jpg";
        //String filePath = "/opt/solo/solo/fase/"+imgName+".jpg";
//        String faceUrl = "https://binguoai.com/images/faces/" + imgName + ".jpg";
        // String faceUrl = "https://hefengwei.com/fase/"+imgName+".jpg";
        boolean flag = base64ToImage(saveOrderForm.getImg64(), filePath);
        if (flag) {
            return updateCustomerFace(fileUrl, saveOrderForm.getShopId().toString(), saveOrderForm.getCashierDeskId());
        } else {
            return ErrorCode.UPLOAD_ERROR;
        }
    }

    /**
     * base64字符串转换成图片 (对字节数组字符串进行Base64解码并生成图片)
     *
     * @param imgStr      base64字符串
     * @param imgFilePath 指定图片存放路径  （注意：带文件名）
     * @return
     */
    public boolean base64ToImage(String imgStr, String imgFilePath) {
        if (StringUtil.isEmpty(imgStr)) {
            // 图像数据为空
            return false;
        }

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            logger.info("base64转图片失败原因:" + e.getMessage());
            return false;
        }
    }

    public ErrorCode updateCustomerFace(String faceUrl, String shopId, Integer cashierDeskId) {
        com.tencentcloudapi.iai.v20180301.models.Result[] results
                = FaceHelperV3.searchFacesFromSingleShop(faceUrl, shopId);
        Integer customerId = null;
        if (results != null && results.length > 0) {
            for (com.tencentcloudapi.iai.v20180301.models.Result result : results) {
                //验证成功策略：confidence值大于90
                if (result.getCandidates()[0].getScore() > 90) {
                    String temp = result.getCandidates()[0].getPersonId();
                    if (temp.contains("_")) {
                        customerId = Integer.valueOf(temp.split("_")[1]);
                    } else {
                        customerId = Integer.valueOf(temp);
                    }
                    return readyOpenCell(customerId, cashierDeskId);
                } else {
                    return ErrorCode.FACE_IDENTIFY;
                }
            }
        }
        return ErrorCode.FACE_IDENTIFY;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByPhone(PhoneMealsForm phoneMealsForm) {
        logger.info("进入手机号存餐订单,入参:" + phoneMealsForm.toString());
        SideBoardVO sideBoardVO = new SideBoardVO();
        Shop shop = shopMapper.selectByPrimaryKey(Shop.builder().id(phoneMealsForm.getShopId()).build());
        if (null == shop.getShopType()) {
            sideBoardVO = aiyouweiService.phoneMeals(phoneMealsForm);
        } else if (2 == shop.getShopType()) {
            Customer customer = isShopCustomer(phoneMealsForm.getPhone(), shop);
            if (null == customer) {
                //return ResultGenerator.genFailResult("非商户绑定用户无法存餐");
                return ErrorCode.NOT_SHOP_VIP;
            }
            logger.info("进入手机号存餐订单,入参:" + phoneMealsForm.toString());
            phoneMealsForm.setShopId(shop.getId());
            sideBoardVO = aiyouweiService.phoneMealApi(phoneMealsForm, customer);
        }
        if (null != sideBoardVO) {
            SaveOrderForm saveOrderForm = SaveOrderForm.builder().branchId(sideBoardVO.getBranchId()).shopId(phoneMealsForm.getShopId())
                    .mealCode(sideBoardVO.getMealCode()).cellNo(phoneMealsForm.getCells()).sideBranchId(sideBoardVO.getSideBranchId())
                    .phone(phoneMealsForm.getPhone()).cashierDeskId(phoneMealsForm.getCashierDeskId())
                    .build();
//            SaveOrderForm saveOrderForm = new SaveOrderForm(null, null, sideBoardVO.getBranchId(), null,
//                    sideBoardVO.getShopId(), sideBoardVO.getMealCode(), null, null, null, null,
//                    sideBoardVO.getSideBranchId(), null, phoneMealsForm.getPhone(), null, phoneMealsForm.getCashierDeskId(), null, null, null,null, null,null,null);
            if (!StringUtils.isEmpty(phoneMealsForm.getCells())) {
                saveOrderForm.setCellNo(phoneMealsForm.getCells());
            }
            logger.info("发送短信取餐码短信，参数:phone" + saveOrderForm.getPhone() + "取餐码:" + saveOrderForm.getMealCode());
            JavaSmsApi.sendQuCanGuiCodeVerify(saveOrderForm.getPhone(), saveOrderForm.getMealCode(), sideBoardVO.getSideBranchId().toString());
            return saveOrderByMealCode(saveOrderForm);
        } else {
            return ErrorCode.SAVE_ORDER_FAIL;
        }
    }

    public Customer isShopCustomer(String phone, Shop shop) {
        return customerMapper.selectCustomerByPhoneAndShopId(phone, shop.getId());
    }

    @Override
    public ErrorCode checkOrderPayStatus(SaveOrderForm saveOrderForm) {
        logger.info("进入查询支付状态接口，入参:" + saveOrderForm);
        String orderId = "";
        if (null != saveOrderForm.getMealCode()) {
            //效验柜子号
            orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
            if (StringUtils.isEmpty(orderId)) {
                return ErrorCode.MEAL_CODE_NOT_EXIST;
            }
            saveOrderForm.setOrderId(orderId);
        } else {
            orderId = saveOrderForm.getOrderId();
        }
        logger.info("调用二维码订单支付状态查询接口，入参:" + orderId);
        JSONObject jsonObject = qrCodePayQCGService.queryPayResult(orderId);
        String code = jsonObject.get("code").toString();
        logger.info("二维码订单支付状态查询完毕,返回值:" + jsonObject.toString());
        if ("1".equals(code)) {
            saveOrderForm.setIsCustomer("true");
            saveOrderForm.setOrderId(saveOrderForm.getOrderId());
            return saveOrderByMealCode(saveOrderForm);
        } else {
            ErrorCode errorCode = ErrorCode.ORDER_NO_PAY;
            saveOrderForm.setOrderId(orderId);
            errorCode.setData(saveOrderForm);
            return ErrorCode.ORDER_NO_PAY;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode getPayCode(SaveOrderForm saveOrderForm) {
        String orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (StringUtils.isEmpty(orderId)) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        saveOrderForm.setOrderId(orderId);
        String code = "";
        try {
            BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
            code = qrCodePayQCGService.createQrCodePayQCG(saveOrderForm.getOrderId(), binguoOrder.getRealfee(), saveOrderForm.getShopId(), saveOrderForm.getPayType());
            saveOrderForm.setImg64(code);
            ErrorCode errorCode = ErrorCode.SUCCESS;
            errorCode.setData(saveOrderForm);
            return errorCode;
        } catch (Exception e) {
            return ErrorCode.GET_PAY_CODE_FAIL;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode beforeOpenCell(SaveOrderForm saveOrderForm) throws Exception {
        String orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        ThirdOrderData thirdOrderData = thirdOrderDataMapper.selectByCode(saveOrderForm.getMealCode(), saveOrderForm.getBranchId(), saveOrderForm.getShopId());
        ZSDOrderInfoForm zsdOrderInfoForm;
        String host = getConfigUrl(1);
        if (thirdOrderData != null) {
            zsdOrderInfoForm = JSON.parseObject(thirdOrderData.getContent(), ZSDOrderInfoForm.class);
            saveOrderForm.setOrderId(thirdOrderData.getOrderNo());
            saveOrderForm.setZsdOrderId(zsdOrderInfoForm.getOrder_id());
            saveOrderForm.setHost(host);
        }
        if (StringUtils.isEmpty(orderId)) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        saveOrderForm.setOrderId(orderId);
        //查询商户id 和 分店id
        BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
        //如果订单是未支付的状态那么则返回401状态码和存取餐数据，让用户选择支付方式
        if (0 == binguoOrder.getPaystatus() && binguoOrder.getRealfee() != 0) {
            ErrorCode errorCode = ErrorCode.ORDER_NO_PAY;
            errorCode.setData(saveOrderForm);
            return errorCode;
        } else {
            return getOrderByMealCode(saveOrderForm);
        }
    }


    @Override
    public ErrorCode getBaiduSdkSerier(String deviceId) {
        ErrorCode errorCode = ErrorCode.SUCCESS;
        logger.info("进入getBaiduSDKSerial方法,入参:" + deviceId);
        String serial = aiyouweiService.getBaiduSDKSerial(deviceId);
        if (null == serial) {
            logger.info("----------该设备未初始化，正在分配序列号,请稍后");
            BaiduSdkSerialNum baiduSdkSerialNum = aiyouweiService.getNoUseBaiduSDKSerial();
            if (null == baiduSdkSerialNum) {
                return ErrorCode.NOT_ENOUGH_SERIAL;
            } else {
                logger.info("----------查找最新一条未使用的序列号:" + baiduSdkSerialNum);
                baiduSdkSerialNum.setDeviceId(deviceId);
                baiduSdkSerialNum.setStatus(true);
                int i = aiyouweiService.serialBindSideBoard(baiduSdkSerialNum);
                if (i > 0) {
                    logger.info("序列号分配成功,号码为:" + baiduSdkSerialNum.getSerialNumber());
                    errorCode.setData(baiduSdkSerialNum.getSerialNumber());
                    return errorCode;
                } else {
                    return ErrorCode.INSERT_OR_UPDATE_ERROR;
                }
            }
        } else {
            logger.info("查询成功,返回结果:" + serial);
            errorCode.setData(serial);
            return errorCode;
        }
    }

    @Override
    public ErrorCode getSideBoardInitStatus(String deviceId) {
        InitInfo initInfo = initInfoMapper.selectByDeviceId(deviceId);
        if (null == initInfo || initInfo.getCashierdeskid() == null) {
            return ErrorCode.DEVICE_NOT_INIT;
        }
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(initInfo.getCashierdeskid());
        if (null == sideBoard.getJpushRegisterId()) {
            return ErrorCode.JPUSH_ID_NOT_EXIST;
        } else {
            ErrorCode errorCode = ErrorCode.SUCCESS;
            errorCode.setData(true);
            return errorCode;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode updateJPushRegisterId(SideBoardVO sideBoardVO) {
        logger.info("sideBoardVO:" + sideBoardVO);
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(sideBoardVO.getCashierDeskId());
        sideBoard.setJpushRegisterId(sideBoardVO.getJpushRegisterId());
        sideBoard.setSideBoardName(sideBoardVO.getName());
        sideBoard.setParentId(0);
        sideBoard.setBoardType(sideBoardVO.getType());
        //查找出
        Integer sideBranchId = sideBoardMapper.selectMaxSideBranchId(sideBoard.getBranchId(), sideBoard.getShopId());
        if (sideBranchId == null) {
            sideBranchId = 0;
        }
        sideBoard.setBranchSideBoardId(sideBranchId + 1);
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        sideBoardMapper.updateByPrimaryKeySelective(sideBoard);
        logger.info("更新sideBoard表成功,更新字段JpushRegisterId，更新值:" + sideBoardVO.getJpushRegisterId());
        List<SideBoardCells> sideBoardCells = new ArrayList<>();
        for (int i = 0; i < sideBoardVO.getCellNum(); i++) {
            sideBoardCells.add(SideBoardCells.builder().id(0).sideBoardId(sideBoard.getId()).isWarm(null)
                    .status(false).cell(i + 1).mealCode(null).orderId(null).build());
        }
        try {
            sideBoardCellsMapper.insertByList(sideBoardCells);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            logger.info("捕获异常:" + e.getMessage());
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        return ErrorCode.SUCCESS;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode addSunSideBoard(SideBoardVO sideBoardVO) {
        logger.info("根据设备id找到主柜id:" + sideBoardVO.getCashierDeskId());
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(sideBoardVO.getCashierDeskId());
        Integer num = sideBoardMapper.selectCount(sideBoard.getId());
        logger.info("设置副柜参数到sideBoard对象");
        sideBoard = SideBoard.builder().id(0).branchId(sideBoardVO.getBranchId()).shopId(sideBoardVO.getShopId()).
                parentId(sideBoard.getId()).status(true).cashierDeskId(sideBoardVO.getCashierDeskId()).
                branchSideBoardId(sideBoard.getBranchSideBoardId()).jpushRegisterId(sideBoard.getJpushRegisterId()).sideBoardName(sideBoard.getSideBoardName() + "-副柜" + num + 1).build();
        sideBoardMapper.insertSelective(sideBoard);
        logger.info("新增sideBoard表成功,新增值:" + sideBoard.toString());
        Integer count = sideBoardMapper.selectCellsCount(sideBoardVO.getCashierDeskId());
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        List<SideBoardCells> sideBoardCells = new ArrayList<>();
        for (int i = 0; i < sideBoardVO.getCellNum(); i++) {
            sideBoardCells.add(SideBoardCells.builder().id(0).sideBoardId(sideBoard.getId()).isWarm(null)
                    .status(false).cell(count + 1 + i).mealCode(null).orderId(null).build());
        }
        try {
            sideBoardCellsMapper.insertByList(sideBoardCells);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            logger.info("捕获异常:" + e.getMessage());
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        logger.info("初始化sideBoardCell表成功");
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(true);
        return errorCode;
    }

    @Override
    public ErrorCode getSunSideBoard(SideBoardVO sideBoardVO) {
        List<SideBoard> sideBoards = sideBoardMapper.selectListByCashierId(sideBoardVO.getCashierDeskId());
        if (sideBoards.size() <= 0 || sideBoards == null) {
            return ErrorCode.DATA_NOT_EXIST;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(sideBoards);
        return errorCode;
    }

    @Override
    public ErrorCode deleteSunSideBoard(SideBoardVO sideBoardVO) {
        logger.info("根据设备id找到主柜id:" + sideBoardVO.getCashierDeskId());
        Integer flag = sideBoardMapper.deleteByPrimaryKey(sideBoardVO.getId());
        Integer result = sideBoardMapper.updateBySideBoardId(sideBoardVO.getId());
        if (flag > 0 && result > 0) {
            return ErrorCode.SUCCESS;
        } else {
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
    }

    @Override
    public ErrorCode generateMiniProgramCode(String cashierDeskId) {
        token = UrlUtils.getAccessToken(WxAppHelper.APPID, WxAppHelper.SECRET).get("access_token").toString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page", "pages/cupboard/index");
        //jsonObject.put("page","pages/me");
        jsonObject.put("scene", cashierDeskId);
        String code = "";
        try {
            code = UrlUtils.sendPostForBuffer(jsonObject, "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
        } catch (Exception e) {
            return ErrorCode.SEND_REQUEST_FAIL;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(code);
        return errorCode;
    }

    @Override
    public ErrorCode getSideBoardByCashierDeskId(Integer cashierDeskId) {
        logger.info("查询取餐柜");
        List<SideBoard> sideBoards = aiyouweiService.getSideBoardByCashierDeskId(cashierDeskId);
        if (sideBoards != null && sideBoards.isEmpty()) {
            ErrorCode errorCode = ErrorCode.SUCCESS;
            errorCode.setData(sideBoards);
            return errorCode;
        } else {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
    }

    /**
     * 获取用户所有的取餐码
     *
     * @param branchId
     * @param shopId
     * @param customerId
     * @return
     */
    @Override
    public ErrorCode getCustomerMealCode(Integer branchId, Integer shopId, Integer customerId) {
        List<String> mealCodes = sideBoardCellDetailMapper.getCustomerMealCodes(customerId, branchId, shopId);
        if (null == mealCodes || mealCodes.isEmpty()) {
            return ErrorCode.MEAL_CODE_NOT_EXIST;
        } else {
            ErrorCode errorCode = ErrorCode.SUCCESS;
            errorCode.setData(mealCodes);
            return errorCode;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByPhoneForJY(PhoneMealsForm phoneMealsForm) throws Exception {
        logger.info("进入手机号存餐订单,入参:" + phoneMealsForm.toString());
        boolean flag = getIsNullByCashierDeskIdAndCell(phoneMealsForm.getCashierDeskId(), phoneMealsForm.getCells());
        if (!flag) {
            return ErrorCode.CELL_IS_USING;
        }
        SideBoardVO sideBoardVO = new SideBoardVO();
        Shop shop = shopMapper.selectByPrimaryKey(Shop.builder().id(phoneMealsForm.getShopId()).build());
        if (null == shop.getShopType()) {
            sideBoardVO = aiyouweiService.phoneMeals(phoneMealsForm);
        } else if (2 == shop.getShopType()) {
            Customer customer = isShopCustomer(phoneMealsForm.getPhone(), shop);
            if (null == customer) {
                return ErrorCode.NOT_SHOP_VIP;
            }
            phoneMealsForm.setName(customer.getName());
            logger.info("进入手机号存餐订单,入参:" + phoneMealsForm.toString());
            phoneMealsForm.setShopId(shop.getId());
            sideBoardVO = aiyouweiService.phoneMealApi(phoneMealsForm, customer);
        }
        if (null != sideBoardVO) {
            SaveOrderForm saveOrderForm = SaveOrderForm.builder().branchId(sideBoardVO.getBranchId()).shopId(phoneMealsForm.getShopId())
                    .mealCode(sideBoardVO.getMealCode()).cellNo(phoneMealsForm.getCells()).sideBranchId(sideBoardVO.getSideBranchId())
                    .phone(phoneMealsForm.getPhone()).cashierDeskId(phoneMealsForm.getCashierDeskId())
                    .build();
//            SaveOrderForm saveOrderForm = new SaveOrderForm(null, null, sideBoardVO.getBranchId(), null,
//                    phoneMealsForm.getShopId(), sideBoardVO.getMealCode(), null, phoneMealsForm.getCells(), null, null,
//                    sideBoardVO.getSideBranchId(), null, phoneMealsForm.getPhone(), null, phoneMealsForm.getCashierDeskId(), null, null, null,null, null,null,null);
            if (StringUtils.isNotBlank(phoneMealsForm.getCells())) {
                saveOrderForm.setCellNo(phoneMealsForm.getCells());
            }

            return saveOrderByPhoneSaveMeals(saveOrderForm, sideBoardVO, null);
        } else {
            return ErrorCode.SAVE_ORDER_FAIL;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByPhoneSaveMeals(SaveOrderForm saveOrderForm, SideBoardVO sideBoardVO, ZSDOrderInfoForm zsdOrderInfoForm) {
        String orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (StringUtils.isEmpty(orderId)) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        saveOrderForm.setOrderId(orderId);
        BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(orderId);
        String[] cellNo = new String[]{saveOrderForm.getCellNo()};
        AiyouweiGetCellVO aiyouweiGetCellVO = sideBoardMapper.selectShopSideBoardInfo(saveOrderForm.getBranchId(), saveOrderForm.getShopId(), saveOrderForm.getCashierDeskId(), saveOrderForm.getCellNo());
        if (aiyouweiGetCellVO == null) {
            return ErrorCode.CELLS_NOT_ENOUGH;
        }
        SideBoard sideBoard = getSideBoardById(aiyouweiGetCellVO.getSideBoardId());

        String mealCode = isMealCodeExist(orderId, saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (StringUtils.isBlank(mealCode)) {
            mealCode = getMealCode(saveOrderForm.getBranchId());
        }
        SideBoardCells boardCells = SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
                status(true).cell(Integer.valueOf(saveOrderForm.getCellNo())).
                orderId(saveOrderForm.getOrderId()).mealCode(mealCode).
                sideBoardId(aiyouweiGetCellVO.getSideBoardId()).isWarm(false).build();
        saveOrderForm.setMealCode(mealCode);
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);
        saveOrderForm.setShopPhone(normalConfigService.getConfigById(4).getValue());
        if (null != zsdOrderInfoForm) {
            ThirdOrderData thirdOrderData = getThirdOrderData(1, zsdOrderInfoForm, saveOrderForm, orderId);
            int flag = thirdOrderDataMapper.insertSelective(thirdOrderData);
            if (flag <= 0) {
                logger.info("第三方订单信息保存失败");
            }
            saveOrderForm.setPhone(zsdOrderInfoForm.getMobile());
        }
        int isMessage = Integer.parseInt(normalConfigService.getConfigById(8).getValue());
        if (isMessage == 1) {
            logger.info("发送短信取餐码短信，参数:phone" + saveOrderForm.getPhone() + "取餐码:" + saveOrderForm.getMealCode());
            SMS sms = JavaSmsApi.sendQuCanGuiCodeVerify(saveOrderForm.getPhone(), saveOrderForm.getMealCode(), sideBoard.getSideBoardName());
            if (sms != null && sms.getCode() != 0) {
                return ErrorCode.SMS_SEND_FAIL;
            }
        }
        if (StringUtils.isEmpty(binguoOrderVO.getOpenId())) {
            if (Integer.parseInt(normalConfigService.getConfigById(9).getValue()) == 0) {
                return ErrorCode.WXGZMESSAGE_PUSH_FAIL;
            }
        } else {
            ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = getZSDWXGongZhongMessageForm(saveOrderForm, sideBoard.getSideBoardName(), ZSDWXMessageTitle.SAVE_ORDER_TITLE.getTitle(), time, "您的订餐已投放至指定取餐柜，请尽快提取，并在一个半小时内食用，谢谢！云餐厅");
            String host = getConfigUrl(1);
            boolean flag = sendWXGongZhoneMessage(binguoOrderVO.getOpenId(), host, zsdwxGongZhongMessageForm);
            if (!flag) {
                return ErrorCode.WXGZMESSAGE_PUSH_FAIL;
            }
        }
        if (saveOrderForm.getOrgin() == null) {
            saveOrderForm.setOrgin(0);
        }
        if (saveOrderForm.getOrgin() == 1) {
            return saveOrderUpdateRecordReturnCellNo(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo, null);
        } else {
            return saveOrderUpdateRecord(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo);
        }

    }

    Boolean getIsNullByCashierDeskIdAndCell(Integer cashierDeskId, String cell) {
        Integer status = sideBoardCellsMapper.selectStatusByCellNoAndCashierDeskId(cashierDeskId, cell);
        return status != 1;
    }

    @Override
    public ErrorCode updateSideBoard(Integer id, String sideBoardName) {
        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(id);
        if (sideBoard == null) {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
        sideBoard.setSideBoardName(sideBoardName);
        int code = sideBoardMapper.updateByPrimaryKeySelective(SideBoard.builder().id(id).sideBoardName(sideBoardName).build());
        if (code < 0) {
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        return ErrorCode.SUCCESS;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByZSDQrCode(SaveOrderForm saveOrderForm) throws Exception {
        NormalConfig normalConfig = normalConfigService.getConfigById(3);
        Map<String, String> map = UrlUtils.urlSplit(saveOrderForm.getOrderUrl());
        Object orderIdObj = map.get("order_id");
        Object typeObj = map.get("type");
        Object storeIdObj = map.get("store_id");
        Integer orderId = orderIdObj == null ? null : Integer.parseInt(orderIdObj.toString());
        Integer type = typeObj == null ? null : Integer.parseInt(typeObj.toString());
        Integer storeId = storeIdObj == null ? null : Integer.parseInt(storeIdObj.toString());
        if (null == type) {
            return ErrorCode.DATA_NOT_EXIST;
        } else {
            if (type != 2) {
                return ErrorCode.CUSTOMER_NOT_ALLOW_SAVE_ORDER;
            }
        }
        String host = getConfigUrl(1);
        String url = host + "/base/store/detail?store_id=" + storeId + "&order_id=" + orderId;
        ZSDOrderInfoForm zsdOrderInfoForm = getZSDOrderInfoForm(url);
        Date date = sideBoardCellDetailMapper.selectSideBoardCellDetailByOrderSN(zsdOrderInfoForm.getOrder_sn());
        if (null != date) {
            int difference = DateUtil.timeDifference(date, new Date());
            if (difference > Integer.parseInt(normalConfig.getValue())) {
                return ErrorCode.SAVE_ORDER_OVER_TIME;
            }
        }
        zsdOrderInfoForm.setType(type);
//        if(null == zsdOrderInfoForm.getOpenId()){
//            return ErrorCode.CUSTOMER_NOT_EXIST;
//        }
        SideBoard sideBoard = sideBoardMapper.selectSideBoardId(saveOrderForm.getCashierDeskId(), saveOrderForm.getBranchId(), saveOrderForm.getShopId());
        if (null == sideBoard) {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
        if (null == zsdOrderInfoForm.getOrderDetailUrl()) {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        } else {
            saveOrderForm.setOrderDetailUrl(zsdOrderInfoForm.getOrderDetailUrl());
        }
        PhoneMealsForm phoneMealsForm =
                PhoneMealsForm.builder().phone(zsdOrderInfoForm.getMobile()).name(zsdOrderInfoForm.getUsername()).
                        shopId(saveOrderForm.getShopId()).branchId(saveOrderForm.getBranchId()).
                        cashierDeskId(saveOrderForm.getCashierDeskId()).isWarm(saveOrderForm.isWarm()).
                        deviceId(sideBoard.getId()).openId(zsdOrderInfoForm.getOpenId()).orderDetailUrl(zsdOrderInfoForm.getOrderDetailUrl()).build();
        SideBoardVO sideBoardVO = aiyouweiService.qrCodePhoneMeals(phoneMealsForm, zsdOrderInfoForm.getOrder_sn());
        if (null == sideBoardVO) {
            return ErrorCode.SAVE_ORDER_FAIL;
        } else {
            String cell = "";
            if (zsdOrderInfoForm.getType() == 2) {
                boolean flag = getIsNullByCashierDeskIdAndCell(saveOrderForm.getCashierDeskId(), saveOrderForm.getCellNo());
                if (!flag) {
                    return ErrorCode.CELL_IS_USING;
                }
                cell = saveOrderForm.getCellNo();
            } else {
                cell = getCellVO(sideBoard.getCashierDeskId(), null);
            }
            if (StringUtils.isEmpty(cell)) {
                return ErrorCode.CELLS_NOT_ENOUGH;
            }
            phoneMealsForm.setCells(cell);
            saveOrderForm = SaveOrderForm.builder().branchId(sideBoardVO.getBranchId()).shopId(phoneMealsForm.getShopId())
                    .mealCode(sideBoardVO.getMealCode()).cellNo(phoneMealsForm.getCells()).sideBranchId(sideBoardVO.getSideBranchId())
                    .phone(zsdOrderInfoForm.getMobile()).cashierDeskId(phoneMealsForm.getCashierDeskId()).orderDetailUrl(zsdOrderInfoForm.getOrderDetailUrl())
                    .orgin(saveOrderForm.getOrgin() == null ? 0 : 1)
                    .build();
//            saveOrderForm = new SaveOrderForm(null, null, sideBoardVO.getBranchId(), null,
//                    phoneMealsForm.getShopId(), sideBoardVO.getMealCode(), null, phoneMealsForm.getCells(), null, null,
//                    sideBoardVO.getSideBranchId(), null, zsdOrderInfoForm.getMobile(), null, phoneMealsForm.getCashierDeskId(),
//                    null, null, null,zsdOrderInfoForm.getOrderDetailUrl(), null,null,saveOrderForm.getOrgin());
            if (StringUtils.isNotBlank(phoneMealsForm.getCells())) {
                saveOrderForm.setCellNo(phoneMealsForm.getCells());
            }

            return saveOrderByPhoneSaveMeals(saveOrderForm, sideBoardVO, zsdOrderInfoForm);

        }
    }

    private String getCellVO(Integer cashierDeskId, List<String> cellNo) {
        String cellNos = sideBoardMapper.selectCellForQrCodeOrder(cashierDeskId, cellNo);
        String key = cellNos + cashierDeskId + "";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 30000, uuid);
        if (lock) {
            return cellNos;
        } else {
            if (null == cellNo) {
                cellNo = new ArrayList<>();
            }
            cellNo.add(cellNos);
            return getCellVO(cashierDeskId, cellNo);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode getOrderByZSDQrCode(SaveOrderForm saveOrderForm) throws Exception {
        Map<String, String> map = UrlUtils.urlSplit(saveOrderForm.getOrderUrl());
        Object orderIdObj = map.get("order_id");
        Object storeIdObj = map.get("store_id");
        Integer orderId = orderIdObj == null ? null : Integer.parseInt(orderIdObj.toString());
        Integer storeId = storeIdObj == null ? null : Integer.parseInt(storeIdObj.toString());
        String host = getConfigUrl(1);
        String url = host + "/base/store/detail?store_id=" + storeId + "&order_id=" + orderId;
        //1.获取访问url得到的内容
        ZSDOrderInfoForm zsdOrderInfoForm = getZSDOrderInfoForm(url);
        SideBoard sideBoard = sideBoardMapper.selectSideBoardId(saveOrderForm.getCashierDeskId(), saveOrderForm.getBranchId(), saveOrderForm.getShopId());
        if (null == sideBoard) {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
//        if(null == zsdOrderInfoForm.getOpenId()){
//            return ErrorCode.CUSTOMER_NOT_EXIST;
//        }

        List<SideBoardCellDetail> sideBoardCellDetails = sideBoardCellDetailMapper.selectSideBoardCellDetail(sideBoard.getId(), zsdOrderInfoForm.getOrder_sn());
        if (sideBoardCellDetails == null || sideBoardCellDetails.isEmpty()) {
            return ErrorCode.MEAL_CODE_NOT_EXIST;
        }
        List<SideBoardCells> sideBoardCells = sideBoardCellsMapper.getSideBoardCellsListBySideBoardCellDetails(sideBoardCellDetails);
        String[] cellNo = new String[sideBoardCells.size()];
        for (int i = 0; i < sideBoardCells.size(); i++) {
            cellNo[i] = sideBoardCells.get(i).getCell().toString();
        }
        String cellNoNum = "";
        for (int i = 0; i < cellNo.length; i++) {
            cellNoNum += cellNo[i];
            if (i <= cellNo.length - 2) {
                cellNoNum += ",";
            }
        }
        saveOrderForm.setCellNo(cellNoNum);
        saveOrderForm.setPhone(zsdOrderInfoForm.getMobile());
        saveOrderForm.setOrderDetailUrl(zsdOrderInfoForm.getOrderDetailUrl());

        if (StringUtils.isEmpty(zsdOrderInfoForm.getOpenId())) {
            if (Integer.parseInt(normalConfigService.getConfigById(9).getValue()) == 0) {
                return ErrorCode.WXGZMESSAGE_PUSH_FAIL;
            }
        } else {
            String strDateFormat = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            String time = sdf.format(sideBoardCellDetails.get(0).getStartTime());
            saveOrderForm.setShopPhone(normalConfigService.getConfigById(4).getValue());
            ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = getZSDWXGongZhongMessageForm(saveOrderForm, sideBoard.getSideBoardName(), ZSDWXMessageTitle.ORDER_GET_TITLE.getTitle(), time, null);
            sendWXGongZhoneMessage(zsdOrderInfoForm.getOpenId(), host, zsdwxGongZhongMessageForm);
        }
        return getOrderUpdateRecord(null, sideBoardCellDetails, cellNo, sideBoard, sideBoardCells, 2, null);

    }

    ZSDOrderInfoForm getZSDOrderInfoForm(String url) {
        ZSDOrderInfoForm zsdOrderInfoForm = new ZSDOrderInfoForm();
        try {
            Map map = UrlUtils.doGet2(url);
            JSONObject jsonObject = (JSONObject) map.get("data");
            zsdOrderInfoForm = JSONObject.toJavaObject(jsonObject, ZSDOrderInfoForm.class);
        } catch (Exception e) {
            throw new ServiceException("URL错误！");
        }
        if (null == zsdOrderInfoForm) {
            throw new ServiceException("订单不存在！");
        }
        return zsdOrderInfoForm;
    }

    @Override
    public Boolean sendWXGongZhoneMessage(String openId, String host, ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm) {
        String url = host + "/Base/WechatTemplate/sendToUsers";
        //String testUrl = "http://gc2.new.zsd.greencampus.me/Base/WechatTemplate/sendToUsers";
        JSONObject first = new JSONObject();
        first.put("value", zsdwxGongZhongMessageForm.getTitle());
        first.put("color", "#173177");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", zsdwxGongZhongMessageForm.getSideBoardName());
        keyword1.put("color", "#173177");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", zsdwxGongZhongMessageForm.getMealCode());
        keyword2.put("color", "#173177");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", zsdwxGongZhongMessageForm.getCellNo());
        keyword3.put("color", "#173177");
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", zsdwxGongZhongMessageForm.getDate().toString());
        keyword4.put("color", "#173177");
        JSONObject keyword5 = new JSONObject();
        keyword5.put("value", zsdwxGongZhongMessageForm.getPhone());
        keyword5.put("color", "#173177");
        JSONObject keyword6 = new JSONObject();
        keyword6.put("value", zsdwxGongZhongMessageForm.getRemark());
        keyword6.put("color", "#173177");
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("remark", keyword6);
        Map<String, String> param = new HashMap<>();
        //JSONObject jsonObject = new JSONObject();
        param.put("openid", openId);
        param.put("url", zsdwxGongZhongMessageForm.getOrderDetailUrl());
        param.put("data", data.toJSONString());
        param.put("template_id", "PlJ9gNzk979YyW7QTLoc31BlrHdZ471YMOekWHtezUs");
        Map map = UrlUtils.send4(url, param);
        Integer flag = wxPushMessageDetailMapper.insertSelective(getWxPushMessageDetailWithBLOBS(param, map));
        return map != null && "S".equals(map.get("status"));
    }

    public static ZSDWXGongZhongMessageForm getZSDWXGongZhongMessageForm(SaveOrderForm saveOrderForm, String sideBoardName, String title, String date, String remark) {
        ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = new ZSDWXGongZhongMessageForm();
        zsdwxGongZhongMessageForm.setTitle(title);
        zsdwxGongZhongMessageForm.setDate(date);
        zsdwxGongZhongMessageForm.setCellNo(saveOrderForm.getCellNo());
        zsdwxGongZhongMessageForm.setSideBoardName(sideBoardName);
        zsdwxGongZhongMessageForm.setPhone(null == saveOrderForm.getShopPhone() ? "" : saveOrderForm.getShopPhone());
        zsdwxGongZhongMessageForm.setMealCode(saveOrderForm.getMealCode());
        zsdwxGongZhongMessageForm.setOrderDetailUrl(saveOrderForm.getOrderDetailUrl());
        if (null == remark) {
            remark = "";
        }
        zsdwxGongZhongMessageForm.setRemark(remark);
        return zsdwxGongZhongMessageForm;
    }

    public String getConfigUrl(Integer id) {
        NormalConfig config = normalConfigService.getConfigById(id);
        return config.getValue();
    }

    @Override
    public List<String> getBinguoOrderIdByMealCodes(String[] mealCodes, Integer shopId, Integer branchId) {
        return sideBoardCellDetailMapper.selectOrderIdByShopIdAndBranchIdAndMealCodes(mealCodes, branchId, shopId);
    }


    ThirdOrderData getThirdOrderData(Integer type, ZSDOrderInfoForm zsdOrderInfoForm, SaveOrderForm saveOrderForm, String orderId) {
        ThirdOrderData thirdOrderData = new ThirdOrderData();
        thirdOrderData.setId(0);
        String content = JSONObject.toJSONString(zsdOrderInfoForm);
        thirdOrderData.setContent(content);
        thirdOrderData.setType(type);
        thirdOrderData.setCreateTime(new Date());
        thirdOrderData.setOrderSn(zsdOrderInfoForm.getOrder_sn());
        thirdOrderData.setOrderNo(orderId);
        thirdOrderData.setShopId(saveOrderForm.getShopId());
        thirdOrderData.setBranchId(saveOrderForm.getBranchId());
        thirdOrderData.setDataOrginUrl(saveOrderForm.getOrderUrl());
        return thirdOrderData;
    }


    WxPushMessageDetailWithBLOBs getWxPushMessageDetailWithBLOBS(Map map1, Map map2) {
        WxPushMessageDetailWithBLOBs wxPushMessageDetailWithBLOBs = new WxPushMessageDetailWithBLOBs();
        wxPushMessageDetailWithBLOBs.setContent(JSONObject.toJSONString(map1));
        wxPushMessageDetailWithBLOBs.setId(0);
        wxPushMessageDetailWithBLOBs.setResult(JSONObject.toJSONString(map2));
        wxPushMessageDetailWithBLOBs.setOpenId(String.valueOf(map1.get("openid")));
        wxPushMessageDetailWithBLOBs.setSendTime(new Date());
        return wxPushMessageDetailWithBLOBs;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode openCellsByCellNoAndUpdateRecode(String cells, Integer id) {
        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(id);
        if (null == sideBoard) {
            return ErrorCode.NET_ERROR;
        }
        String[] cellNos = cells.split(",");
        List<SideBoardCellDetail> sideBoardCellDetails = sideBoardCellDetailMapper.selectSideBoardCellDetailByCellNo(id, cellNos);
        if (sideBoardCellDetails == null || sideBoardCellDetails.isEmpty()) {
            return ErrorCode.YZF_ORDER_ERROR;
        }
        List<SideBoardCells> sideBoardCells = sideBoardCellsMapper.getSideBoardCellsListBySideBoardCellDetails(sideBoardCellDetails);
        if (sideBoardCells == null || sideBoardCells.isEmpty()) {
            return ErrorCode.NET_ERROR;
        }
        return getOrderUpdateRecord(null, sideBoardCellDetails, cellNos, sideBoard, sideBoardCells, 3, null);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderUpdateRecordReturnCellNo(SideBoardCells boardCells, SaveOrderForm saveOrderForm, BinguoOrderVO binguoOrderVO, SideBoard sideBoard, String[] cellNo, BinguoOrder binguoOrder) {
        //只回滚以下异常，
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            if (binguoOrder != null) {
                binguoOrderMapper.updateByPrimaryKeySelective(binguoOrder);
            }
            sideBoardCellsMapper.updateSideBoardCells(boardCells);
            List<SideBoardCellDetail> sideBoardCellDetails = sideBoardCellDetailMapper.selectByOrderId(saveOrderForm.getOrderId());
            List<SideBoardCells> sideBoardCells = sideBoardCellsMapper.selectByOrderId(saveOrderForm.getOrderId());

            if (sideBoardCells.size() <= sideBoardCellDetails.size()) {
                //todo 这里当初为什么会选用get(0)的方式呢？
                sideBoardCellDetails.get(0).setStartTime(new Timestamp(System.currentTimeMillis()));
                sideBoardCellDetails.get(0).setCell(boardCells.getCell().toString());
                sideBoardCellDetails.get(0).setOrderStatus(1);
                sideBoardCellDetails.get(0).setSideBoardId(sideBoard.getId());
                sideBoardCellDetails.get(0).setPhone(saveOrderForm.getPhone());
                logger.info("存餐更新:sideBoardCellDetail:" + sideBoardCellDetails);
                sideBoardCellDetailMapper.updateByPrimaryKeySelective(sideBoardCellDetails.get(0));
            } else {
                //新增一个8参构造，代码看上去更简洁了
                SideBoardCellDetail sideBoardCellDetail =
                        new SideBoardCellDetail(0, saveOrderForm.getOrderId(), new Timestamp(System.currentTimeMillis()),
                                saveOrderForm.getBranchId(), saveOrderForm.getShopId(), saveOrderForm.getMealCode(), boardCells.getCell().toString(), 1, sideBoard.getId(), saveOrderForm.getPhone() == null ? null : saveOrderForm.getPhone());
                logger.info("存餐新建sideBoardCellDetail:" + sideBoardCellDetail);
                sideBoardCellDetailMapper.insertSelective(sideBoardCellDetail);
            }
            if (!StringUtils.isEmpty(saveOrderForm.getHost())) {
                CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
                    //异步发送取餐信息
                    updateZSDOrderStatus(saveOrderForm);
                    return true;
                });
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            //try  catch 结构和@Transactional同样监听的是Exception类，所以这里自动回滚不会生效，手动加上回滚语句
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(cellNo);
        return errorCode;
    }


    public Boolean getCashierDeskByCcode(String cCode) {
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode getOrderUpdateRecordReturnCode(BinguoOrderVO binguoOrderVO, List<SideBoardCellDetail> list, String[] cellNo, SideBoard sideBoard, List<SideBoardCells> slist, Integer status, SaveOrderForm saveOrderForm) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setOrderStatus(status);
            list.get(i).setEndTime(new Timestamp(new Date().getTime()));
        }
        List<SideBoardCells> sideBoardCells = new ArrayList<>();
        for (SideBoardCells sideBoardCell : slist) {
            sideBoardCell.setStatus(false);
            sideBoardCell.setOrderId("");
            sideBoardCell.setMealCode("");
            sideBoardCell.setIsWarm(false);
            sideBoardCells.add(sideBoardCell);
        }
        //只回滚以下异常，
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            sideBoardCellDetailMapper.updateSideBoardCellDetailsByList(list);
            sideBoardCellsMapper.updateSideBoardCellsByList(sideBoardCells);
            if (saveOrderForm != null) {
                saveOrderForm.setType(2);
                if (!StringUtils.isEmpty(saveOrderForm.getHost())) {
                    CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
                        //异步发送取餐信息
                        updateZSDOrderStatus(saveOrderForm);
                        return true;
                    });
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            //try  catch 结构和@Transactional同样监听的是Exception类，所以这里自动回滚不会生效，手动加上回滚语句
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ErrorCode.EXCEPTION_ROLLBACK;
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(cellNo);
        return errorCode;
    }

    @Override
    public ErrorCode getAllCustomerBoard(Integer branchId, Integer cashierDeskId) {
        List<SideBoard> sideBoardList = sideBoardMapper.selectAllCustomerBoard(branchId, cashierDeskId);
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(sideBoardList);
        return errorCode;
    }

    @Override
    public ErrorCode bindCustomerBoard(BindCustomerBoardForm form) {
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(form.getCashierDeskId());
        if (sideBoard.getId().equals(form.getCustomerBoardId())) {
            return ErrorCode.BIND_ID_ERROR;
        }
        sideBoard.setBindBoard(form.getCustomerBoardId());
        int result = sideBoardMapper.updateByPrimaryKeySelective(sideBoard);
        if (result > 0) {
            return ErrorCode.SUCCESS;
        }
        return ErrorCode.INSERT_OR_UPDATE_ERROR;
    }

    @Override
    public ErrorCode hendaGetOrder(SaveOrderForm saveOrderForm) {
        SbThirdOrder sbThirdOrder = new SbThirdOrder();
        //查找到存餐柜对应绑定的柜子
        SideBoard sideBoard = sideBoardMapper.selectBindBoardByCashierIdAndBoardType(saveOrderForm.getCashierDeskId());
        if (sideBoard == null) {
            //没查到对应的柜子代表未完成绑定操作
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        List<SbThirdOrderDetail> sbThirdOrderDetailList = new ArrayList<>();
        //传入取餐码
        if (StringUtils.isEmpty(saveOrderForm.getMealCode()) && !StringUtils.isEmpty(saveOrderForm.getOrderId())) {
            sbThirdOrder = sbThirdOrderMapper.selectByOrderId(saveOrderForm.getOrderId());
            //传入订单号
        } else if (!StringUtils.isEmpty(saveOrderForm.getMealCode()) && StringUtils.isEmpty(saveOrderForm.getOrderId())) {
            sbThirdOrder = sbThirdOrderMapper.selectByOrderId(saveOrderForm.getOrderId());
        }
        // 判断订单是否存在数据库
        if (sbThirdOrder == null) {
            //不存在 判断是否需要请求第三方订单接口
            SbConfig isNeedGetOrderInfo = sbConfigMapper.selectConfig(sideBoard.getId(), SbConfigKey.IS_NEED_GET_ORDER_INFO.getKey());
            //1需要  0 不需要
            if (Integer.parseInt(isNeedGetOrderInfo.getValue()) == 1) {
                SbConfig orderInfoInterface = sbConfigMapper.selectConfig(sideBoard.getId(), SbConfigKey.IS_NEED_GET_ORDER_INFO.getKey());
                if (orderInfoInterface.getValue() != null) {
                    //todo 请求第三方接口，目前没有接口文档给过来所以数据格式接口信息均待定
                    /**
                     * 需要就请求第三方订单并将请求到的数据插入到数据库，并返回所有未取餐品让用户选择是否取餐以及取哪些餐
                     * 用户取餐，根据用户选择的餐品更新数据库，更新binguo_order表、取餐柜detail表、以及cell表
                     * 用户不取餐结束此次交互
                     * 不需要就返回订单不存在提示
                     */
                }
                return ErrorCode.YZF_ORDER_ERROR;
            }
            return ErrorCode.YZF_ORDER_ERROR;
        }
        sbThirdOrderDetailList = sbThirdOrderDetailMapper.selectByOrderIdAndStatus(sbThirdOrder.getOrderId(), 1);
        //存在  查询订单是否还有未取餐品
        if (sbThirdOrderDetailList == null) {
            return ErrorCode.YZF_ORDER_ERROR;
        }
        //有的话返回所有未取餐品让用户选择是否取餐以及取哪些餐
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(sbThirdOrderDetailList);
        /**
         *     用户取餐，根据用户选择的餐品更新数据库，更新binguo_order表、取餐柜detail表、以及cell表
         *     用户不取餐结束此次交互
         *     没有的话返回订单已失效提示
         */
        return errorCode;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode hendaSaveOrder(SaveOrderForm saveOrderForm) throws Exception {
        //查找到存餐柜对应绑定的柜子
        SideBoard sideBoard = sideBoardMapper.selectBindBoardByCashierIdAndBoardType(saveOrderForm.getCashierDeskId());
        if (sideBoard == null) {
            //没查到对应的柜子代表未完成绑定操作
            return ErrorCode.INSERT_OR_UPDATE_ERROR;
        }
        /**
         * 1.入参为餐柜号，餐格号，动作，其它(人员，来源1.APP(餐柜)/2.小程序/3.H5/4.Web/30.APP(其它))
         * 2.动作
         *      ①.重存
         *          1.2 生成新餐格订单(使用配置中餐格对应的商品) 返回前端
         *      ②.置空
         *          2.1 对应餐格没有有效或过期订单　则返回正常
         *          2.2 对应餐格已有订单且有效：订单状态置为重存无效，若有订单且为过期状态则状态置为过期无效
         *          2.3 返回前端
         *      ③.存餐 生成新餐格订单(使用配置中餐格对应的商品) 返回前端
         */
        System.out.println("key:" + SbConfigKey.OVERTIME_MIN.getKey());
        SbConfig overTime = sbConfigMapper.selectConfig(sideBoard.getId(), SbConfigKey.OVERTIME_MIN.getKey());
        List<SideBoardCellDetail> sideBoardCellDetailList = new ArrayList<>();
        List<SideBoardCells> sideBoardCellsList = new ArrayList<>();
        String[] cellNo = new String[]{saveOrderForm.getCellNo()};
        SbBindProductToCell sbBindProductToCell = sbBindProductToCellMapper.selectBySideBoardAndCell(sideBoard.getId(), Integer.valueOf(saveOrderForm.getCellNo()));
        if (sbBindProductToCell == null) {
            return ErrorCode.CELL_BIND_PRODUCT_NOT_EAXIST;
        }
        Product product = productMapper.selectByPrimaryKey(sbBindProductToCell.getProductId());
        if (product == null) {
            return ErrorCode.CELL_BIND_PRODUCT_STATUS_ERROR;
        }
        PhoneMealsForm phoneMealsForm = new PhoneMealsForm();
        phoneMealsForm.setCells(saveOrderForm.getCellNo());
        phoneMealsForm.setWarm(false);
        phoneMealsForm.setCashierDeskId(saveOrderForm.getCashierDeskId());
        phoneMealsForm.setShopId(saveOrderForm.getShopId());
        phoneMealsForm.setBranchId(saveOrderForm.getBranchId());
        //存餐
        if (saveOrderForm.getAction() == 3) {
            //存餐
            return hendaSaveOrderByProduct(phoneMealsForm, product, sideBoard);
            //这里直接return 结果
        } else {
            //重存与置空都需要先置空判断，实际上也是可以复用
            //1.判断当前餐格内是否有订单 以及订单状态
            SideBoardCellDetail sideBoardCellDetail = sideBoardCellDetailMapper.selectSideBoardCellDetailCellByHendDa(sideBoard.getId(), saveOrderForm.getCellNo(), saveOrderForm.getBranchId(), saveOrderForm.getShopId());
            sideBoardCellDetailList.add(sideBoardCellDetail);
            //餐格无订单
            if (sideBoardCellDetail == null) {
                return ErrorCode.SUCCESS;
            } else {
                List<String> orderList = new ArrayList<String>();
                orderList.add(sideBoardCellDetail.getOrderId());
                sideBoardCellsList = sideBoardCellsMapper.selectByOrderIds(orderList);
                //1.1 对应餐格已有订单且有效
                if (Integer.valueOf(overTime.getValue()) - (DateUtil.timeDifference(sideBoardCellDetail.getStartTime(), new Date())) > 0) {
                    getOrderUpdateRecordReturnCode(null, sideBoardCellDetailList, cellNo, sideBoard, sideBoardCellsList, 3, null);
                    //
                } else {
                    //订单状态置为重存无效，若有订单且为过期状态则状态置为过期无效
                    getOrderUpdateRecordReturnCode(null, sideBoardCellDetailList, cellNo, sideBoard, sideBoardCellsList, 4, null);
                }
                if (saveOrderForm.getAction() == 1) {
                    //重存与置空的区别就是重存会生成新的订单，置空不会
                    //把存餐逻辑封装一下这里可以复用
                    ErrorCode errorCode = hendaSaveOrderByProduct(phoneMealsForm, product, sideBoard);
                    return errorCode;
                } else {
                    return ErrorCode.SUCCESS;
                }
            }
        }
    }

    private ErrorCode hendaSaveOrderByProduct(PhoneMealsForm form, Product product, SideBoard sideBoard) throws Exception {
        SideBoardVO sideBoardVO = aiyouweiService.saveHdOrder(form, product);
        if (null != sideBoardVO) {
            //恒大存餐无短信无微信逻辑
            SaveOrderForm saveOrderForm = SaveOrderForm.builder().branchId(sideBoardVO.getBranchId()).shopId(form.getShopId())
                    .mealCode(sideBoardVO.getMealCode()).cellNo(form.getCells()).sideBranchId(sideBoardVO.getSideBranchId())
                    .phone(form.getPhone()).cashierDeskId(form.getCashierDeskId())
                    .build();
            if (StringUtils.isNotBlank(form.getCells())) {
                saveOrderForm.setCellNo(form.getCells());
            }
            return saveOrderByHdSaveMeals(saveOrderForm, sideBoard);
        } else {
            return ErrorCode.SAVE_ORDER_FAIL;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByHdSaveMeals(SaveOrderForm saveOrderForm, SideBoard sideBoard) {
        String orderId = getBinguoOrderId(saveOrderForm.getMealCode(), saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (StringUtils.isEmpty(orderId)) {
            return ErrorCode.CUSTOMER_NOT_ORDER;
        }
        saveOrderForm.setOrderId(orderId);
        BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(orderId);
        String[] cellNo = new String[]{saveOrderForm.getCellNo()};
        String mealCode = isMealCodeExist(orderId, saveOrderForm.getShopId(), saveOrderForm.getBranchId());
        if (StringUtils.isBlank(mealCode)) {
            mealCode = getMealCode(saveOrderForm.getBranchId());
        }
        SideBoardCells boardCells = sideBoardCellsMapper.selectBySideBoardAndCell(sideBoard.getId(), saveOrderForm.getCellNo());
        boardCells.setStatus(true);
        boardCells.setMealCode(mealCode);
        boardCells.setIsWarm(false);
        boardCells.setOrderId(orderId);
        saveOrderForm.setMealCode(mealCode);
        return saveOrderUpdateRecordReturnCellNo(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo, null);
    }

    /**
     * 预订单生成
     *
     * @param saveOrderForm
     * @return
     * @throws ParseException
     */
    @Override
    public ErrorCode getMealCodeByOrderUrl(SaveOrderForm saveOrderForm) throws ParseException {
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", saveOrderForm.getAppId());
        param.put("orderUrl", saveOrderForm.getOrderUrl());
        String key = apiService.getKeyByAppID(saveOrderForm.getAppId());
        String sign = ApiController.generateSign(param, key);
        logger.info("效验签名！  传入签名:" + saveOrderForm.getSign() + "生成签名:" + sign);
        if (!saveOrderForm.getSign().equals(sign)) {
            return ErrorCode.SIGN_ERROR;
        }
        NormalConfig normalConfig = normalConfigService.getConfigById(3);
        NormalConfig shopId = normalConfigService.getConfigById(10);
        NormalConfig branchId = normalConfigService.getConfigById(11);
        saveOrderForm.setShopId(Integer.valueOf(shopId.getValue()));
        saveOrderForm.setBranchId(Integer.valueOf(branchId.getValue()));
        Map<String, String> map = UrlUtils.urlSplit(saveOrderForm.getOrderUrl());
        Object orderIdObj = map.get("order_id");
        Object typeObj = map.get("type");
        Object storeIdObj = map.get("store_id");
        Integer orderId = orderIdObj == null ? null : Integer.parseInt(orderIdObj.toString());
        Integer type = typeObj == null ? null : Integer.parseInt(typeObj.toString());
        Integer storeId = storeIdObj == null ? null : Integer.parseInt(storeIdObj.toString());
        if (null == type) {
            return ErrorCode.DATA_NOT_EXIST;
        } else {
            if (type != 2) {
                return ErrorCode.CUSTOMER_NOT_ALLOW_SAVE_ORDER;
            }
        }
        String host = getConfigUrl(1);
        String url = host + "/base/store/detail?store_id=" + storeId + "&order_id=" + orderId;
        ZSDOrderInfoForm zsdOrderInfoForm = getZSDOrderInfoForm(url);
        Date date = sideBoardCellDetailMapper.selectSideBoardCellDetailByOrderSN(zsdOrderInfoForm.getOrder_sn());
        if (null != date) {
            int difference = DateUtil.timeDifference(date, new Date());
            if (difference > Integer.parseInt(normalConfig.getValue())) {
                return ErrorCode.SAVE_ORDER_OVER_TIME;
            }
        }
        zsdOrderInfoForm.setType(type);
        //订单预生成
        PhoneMealsForm phoneMealsForm =
                PhoneMealsForm.builder().phone(zsdOrderInfoForm.getMobile()).name(zsdOrderInfoForm.getUsername()).
                        shopId(saveOrderForm.getShopId()).branchId(saveOrderForm.getBranchId()).
                        cashierDeskId(null).isWarm(saveOrderForm.isWarm()).
                        deviceId(null).openId(zsdOrderInfoForm.getOpenId()).orderDetailUrl(zsdOrderInfoForm.getOrderDetailUrl()).build();
        //生成订单与取餐码
        Map<String, String> resultMap = aiyouweiService.prepareQrCodePhoneMeals(phoneMealsForm, zsdOrderInfoForm.getOrder_sn());
        if (resultMap.get("code") == null) {
            return ErrorCode.PREPARE_ORDER_FAIL;
        }
        ThirdOrderData thirdOrderData = getThirdOrderData(1, zsdOrderInfoForm, saveOrderForm, resultMap.get("orderNo"));
        thirdOrderData.setMealCode(resultMap.get("code"));
        thirdOrderData.setDataOrginUrl(url);
        Integer flag = thirdOrderDataMapper.insertSelective(thirdOrderData);
        if (flag <= 0) {
            logger.info("第三方订单信息保存失败");
        }
        ErrorCode errorCode = ErrorCode.SUCCESS;
        errorCode.setData(resultMap.get("code"));
        return errorCode;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByZSDQrCodeOrMealCode(SaveOrderForm saveOrderForm) {
        ZSDOrderInfoForm zsdOrderInfoForm;
        ThirdOrderData thirdOrderData = new ThirdOrderData();
        String host = getConfigUrl(1);
        if (saveOrderForm.getMealCode() != null && saveOrderForm.getOrderDetailUrl() == null) {
            thirdOrderData = thirdOrderDataMapper.selectByCode(saveOrderForm.getMealCode(), saveOrderForm.getBranchId(), saveOrderForm.getShopId());
            saveOrderForm.setHost(host);
        } else if (saveOrderForm.getMealCode() == null && saveOrderForm.getOrderUrl() != null) {
            Map<String, String> map = UrlUtils.urlSplit(saveOrderForm.getOrderUrl());
            Object orderIdObj = map.get("order_id");
            Object typeObj = map.get("type");
            Object storeIdObj = map.get("store_id");
            Integer orderId = orderIdObj == null ? null : Integer.parseInt(orderIdObj.toString());
            Integer type = typeObj == null ? null : Integer.parseInt(typeObj.toString());
            Integer storeId = storeIdObj == null ? null : Integer.parseInt(storeIdObj.toString());
            if (null == type) {
                return ErrorCode.DATA_NOT_EXIST;
            } else {
                if (type != 2) {
                    return ErrorCode.CUSTOMER_NOT_ALLOW_SAVE_ORDER;
                }
            }
            String url = host + "/base/store/detail?store_id=" + storeId + "&order_id=" + orderId;
            thirdOrderData = thirdOrderDataMapper.selectByOrderUrl(url, saveOrderForm.getBranchId(), saveOrderForm.getShopId());
            saveOrderForm.setOrderUrl(url);
            saveOrderForm.setType(type);
            if (orderId != null) {
                saveOrderForm.setOrderId(orderId.toString());
            }
        }
        zsdOrderInfoForm = JSON.parseObject(thirdOrderData.getContent(), ZSDOrderInfoForm.class);
        saveOrderForm.setOrderId(thirdOrderData.getOrderNo());
        saveOrderForm.setZsdOrderId(zsdOrderInfoForm.getOrder_id());
        return saveOrderByZSDQrCodeOrMealCodeUpdateData(saveOrderForm, thirdOrderData, zsdOrderInfoForm);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ErrorCode saveOrderByZSDQrCodeOrMealCodeUpdateData(SaveOrderForm saveOrderForm, ThirdOrderData thirdOrderData, ZSDOrderInfoForm zsdOrderInfoForm) {
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(saveOrderForm.getCashierDeskId());
        if (sideBoard == null) {
            return ErrorCode.SIDE_BOARD_NOT_EXIST;
        }
        AiyouweiGetCellVO aiyouweiGetCellVO = sideBoardMapper.selectShopSideBoardInfo(saveOrderForm.getBranchId(), saveOrderForm.getShopId(), saveOrderForm.getCashierDeskId(), saveOrderForm.getCellNo());
        if (aiyouweiGetCellVO == null) {
            return ErrorCode.CELLS_NOT_ENOUGH;
        }
//        SideBoardCellDetail sideBoardCellDetail = sideBoardCellDetailMapper.selectSideBoardCellDetailCell(saveOrderForm.getMealCode(),saveOrderForm.getBranchId(),saveOrderForm.getShopId(),Integer.valueOf(2));
//        if(sideBoardCellDetail == null){
//            return ErrorCode.YZF_ORDER_ERROR;
//        }
        String[] cellNo = new String[]{saveOrderForm.getCellNo()};
        BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(thirdOrderData.getOrderNo());
        SideBoardCells boardCells = SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
                status(true).cell(Integer.valueOf(saveOrderForm.getCellNo())).
                orderId(saveOrderForm.getOrderId()).mealCode(thirdOrderData.getMealCode()).
                sideBoardId(aiyouweiGetCellVO.getSideBoardId()).isWarm(false).build();
        saveOrderForm.setMealCode(thirdOrderData.getMealCode());
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);
        saveOrderForm.setShopPhone(normalConfigService.getConfigById(4).getValue());
        saveOrderForm.setPhone(zsdOrderInfoForm.getMobile());
        int isMessage = Integer.parseInt(normalConfigService.getConfigById(8).getValue());
        if (isMessage == 1) {
            logger.info("发送短信取餐码短信，参数:phone" + saveOrderForm.getPhone() + "取餐码:" + saveOrderForm.getMealCode());
            SMS sms = JavaSmsApi.sendQuCanGuiCodeVerify(saveOrderForm.getPhone(), saveOrderForm.getMealCode(), sideBoard.getSideBoardName());
            if (sms != null && sms.getCode() != 0) {
                return ErrorCode.SMS_SEND_FAIL;
            }
        }
        if (StringUtils.isEmpty(binguoOrderVO.getOpenId())) {
            if (Integer.parseInt(normalConfigService.getConfigById(9).getValue()) == 0) {
                return ErrorCode.WXGZMESSAGE_PUSH_FAIL;
            }
        } else {
            ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = getZSDWXGongZhongMessageForm(saveOrderForm, sideBoard.getSideBoardName(), ZSDWXMessageTitle.SAVE_ORDER_TITLE.getTitle(), time, "您的订餐已投放至指定取餐柜，请尽快提取，并在一个半小时内食用，谢谢！云餐厅");
            String host = getConfigUrl(1);
            boolean flag = sendWXGongZhoneMessage(binguoOrderVO.getOpenId(), host, zsdwxGongZhongMessageForm);
            if (!flag) {
                return ErrorCode.WXGZMESSAGE_PUSH_FAIL;
            }
        }
        if (saveOrderForm.getOrgin() == null) {
            saveOrderForm.setOrgin(0);
        }

        BinguoOrder binguoOrder = binguoOrderMapper.findByOrderNo(thirdOrderData.getOrderNo());
        binguoOrder.setCashierdeskid(saveOrderForm.getCashierDeskId());
        if (saveOrderForm.isWarm()) {
            binguoOrder.setIsWarm(1);
        }
        saveOrderForm.setType(1);
        if (saveOrderForm.getOrgin() == 1) {
            return saveOrderUpdateRecordReturnCellNo(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo, binguoOrder);
        } else {
            return saveOrderUpdateRecord(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo);
        }
    }


    public void updateZSDOrderStatus(SaveOrderForm saveOrderForm) {
        try {
            logger.info("进入updateZSDOrderStatus");
            Map map = new HashMap<String, Object>();
            TreeMap<String, String> param = new TreeMap<>();
            param.put("id", saveOrderForm.getZsdOrderId());
            param.put("type", saveOrderForm.getType().toString());
            String key = getConfigUrl(12);
            String sign = ApiController.generateSign(param, key);
            param.put("sign", sign.toLowerCase());
            logger.info(param.toString());
            map = UrlUtils.send4(saveOrderForm.getHost() + "/base/store/update", param);
            logger.info("修改青橄榄状态返回结果:" + map);
        } catch (Exception e) {
            logger.info("修改失败，原因:" + e.getMessage());
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    @Override
    public ErrorCode saveOrderByChooseCellNo(SaveOrderForm saveOrderForm) {
        SideBoard sideBoard = sideBoardMapper.selectByCashierId(saveOrderForm.getCashierDeskId());
        AiyouweiGetCellVO aiyouweiGetCellVO = sideBoardMapper.selectShopSideBoardInfo(saveOrderForm.getBranchId(), saveOrderForm.getShopId(), saveOrderForm.getCashierDeskId(), saveOrderForm.getCellNo());
        if (aiyouweiGetCellVO == null) {
            return ErrorCode.CELLS_NOT_ENOUGH;
        }
        String[] cellNo = new String[]{saveOrderForm.getCellNo()};
        SideBoardCellDetail sideBoardCellDetail = sideBoardCellDetailMapper.selectSideBoardCellDetailCell(saveOrderForm.getMealCode(), saveOrderForm.getBranchId(), saveOrderForm.getShopId(), 2);
        if (sideBoardCellDetail == null) {
            return ErrorCode.YZF_ORDER_ERROR;
        }
        if (sideBoardCellDetail.getPhone() != null) {
            saveOrderForm.setPhone(sideBoardCellDetail.getPhone());
        }
        saveOrderForm.setOrderId(sideBoardCellDetail.getOrderId());
        BinguoOrderVO binguoOrderVO = getBinguoOrderByOrderNo(sideBoardCellDetail.getOrderId());
        SideBoardCells boardCells = SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
                status(true).cell(Integer.valueOf(saveOrderForm.getCellNo())).
                orderId(saveOrderForm.getOrderId()).mealCode(saveOrderForm.getMealCode()).
                sideBoardId(aiyouweiGetCellVO.getSideBoardId()).isWarm(false).build();
        saveOrderForm.setMealCode(saveOrderForm.getMealCode());
        if (saveOrderForm.getOrgin() == null) {
            saveOrderForm.setOrgin(0);
        }
        BinguoOrder binguoOrder = binguoOrderMapper.findByOrderNo(sideBoardCellDetail.getOrderId());
        binguoOrder.setCashierdeskid(saveOrderForm.getCashierDeskId());
        String key = SbConfigKey.MESSAGE_SWITCH.getKey() + sideBoard.getBranchId();
        SbConfig sbConfig = sbConfigMapper.selectConfigByKey(key);
        if (sbConfig != null) {
            if (Integer.parseInt(sbConfig.getValue()) == 1) {
                logger.info("发送短信取餐码短信，参数:phone" + binguoOrder.getCustomerphone() + "取餐码:" + saveOrderForm.getMealCode());
                SMS sms = JavaSmsApi.sendQuCanGuiCodeVerify(binguoOrder.getCustomerphone(), saveOrderForm.getMealCode(), sideBoard.getSideBoardName());
                if (sms != null && sms.getCode() != 0) {
                    if (sms.getCode() == 53) {
                        return ErrorCode.SMS_SEND_TOO_MUCH;
                    } else {
                        return ErrorCode.SMS_SEND_FAIL;
                    }
                }
            }
        }
        if (saveOrderForm.isWarm()) {
            binguoOrder.setIsWarm(1);
        }
        if (saveOrderForm.getOrgin() == 1) {
            return saveOrderUpdateRecordReturnCellNo(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo, binguoOrder);
        } else {
            return saveOrderUpdateRecord(boardCells, saveOrderForm, binguoOrderVO, sideBoard, cellNo);
        }
    }


}
